import pandas as pd
import csv
from tkinter import filedialog
from tkinter import Tk


def extract_coordinates(coord_str):
    try:
        x_val = int(coord_str.split('Y')[0].split('X')[1])
        y_val = int(coord_str.split('Y')[1])
        return x_val, y_val
    except Exception:
        return None, None

def create_visualization_map(input_file, output_file):
    df = pd.read_csv(input_file, header=None, skiprows=13, usecols=[1, 11], dtype={1: str, 11: str})
    df.dropna(inplace=True)

    # Create a dictionary to store soft bin values against coordinates    xy_dict = {}
    for _, row in df.iterrows():
        x, y = extract_coordinates(row[1])
        if x is not None and y is not None:
            xy_dict[(x, y)] = row[11]

    # Identify the min and max X, Y values to create a grid    all_x = [key[0] for key in xy_dict.keys()]
    all_y = [key[1] for key in xy_dict.keys()]

    min_x, max_x = min(all_x), max(all_x)
    min_y, max_y = min(all_y), max(all_y)

    # Create the grid and fill in the values    data = []
    for y in range(min_y, max_y + 1):
        row = [''] * 8  # Adding 8 empty strings at the beginning of each row        for x in range(min_x, max_x + 1):
            if (x, y) in xy_dict:
                row.append(xy_dict[(x, y)])
            else:
                row.append('')
        data.append(row)

    # Write the data to the CSV file    with open(output_file, 'w', newline='') as f:
        writer = csv.writer(f)
        writer.writerows(data)


def main():
    root = Tk()
    root.withdraw()  # This just hides the main window    input_file = filedialog.askopenfilename(title="Select the modified CSV file")
    output_file = filedialog.asksaveasfilename(title="Save the visualization map as", defaultextension=".csv", filetypes=[("CSV files", "*.csv")])

    if not input_file or not output_file:
        print("Operation cancelled.")
        return
    create_visualization_map(input_file, output_file)


if __name__ == "__main__":
    main()